package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConStant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUps(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到Es
        //建立一个索引 product映射关系

        //保存
        BulkRequest request = new BulkRequest();
        skuEsModels.forEach(item->{
            IndexRequest indexRequest = new IndexRequest(EsConStant.PRODUCT_INDEX);
            indexRequest.id(item.getSkuId().toString());
            //内容 JSON
            String s = JSON.toJSONString(item);
            indexRequest.source(s, XContentType.JSON);
            request.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();//是否有错误,没错误返回false

        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());//每个处理结果
        log.error("商品上架错误 :{}，返回数据{}"+collect,bulk.toString());

        return b;
    }
}
